package com.java110.mall.chain.adapt.order;

import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.SendSmsFactory;
import com.java110.dto.data.DatabusDataDto;
import com.java110.dto.privilege.BasePrivilegeDto;
import com.java110.dto.privilege.PrivilegeDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.shopSms.ShopSmsDto;
import com.java110.dto.shopSmsDetail.ShopSmsDetailDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.IStoreOrderInnerServiceSMO;
import com.java110.intf.chain.IPrintOrderV1InnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.shop.IShopSmsDetailV1InnerServiceSMO;
import com.java110.intf.shop.IShopSmsV1InnerServiceSMO;
import com.java110.intf.user.IPrivilegeUserV1InnerServiceSMO;
import com.java110.intf.user.IPrivilegeV1InnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.mall.chain.adapt.IDatabusAdapt;
import com.java110.po.shopSms.ShopSmsPo;
import com.java110.po.shopSmsDetail.ShopSmsDetailPo;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 发送
 */
@Service("sendOrderSmsDataBus")
public class SendOrderSmsDataBus implements IDatabusAdapt {

    @Autowired
    private IShopSmsV1InnerServiceSMO shopSmsV1InnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IStoreOrderInnerServiceSMO storeOrderInnerServiceSMOImpl;

    @Autowired
    private IPrivilegeV1InnerServiceSMO privilegeV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IShopSmsDetailV1InnerServiceSMO shopSmsDetailV1InnerServiceSMOImpl;



    @Override
    public void execute(DatabusDataDto databusDataDto) throws Exception {

        String orderId = databusDataDto.getBusinessId();
        if (StringUtil.isEmpty(orderId)) {
            throw new IllegalArgumentException("未包含订单ID");
        }

        StoreOrderDto storeOrderDto = new StoreOrderDto();
        storeOrderDto.setOrderId(orderId);
        List<StoreOrderDto> storeOrderDtos = storeOrderInnerServiceSMOImpl.queryStoreOrders(storeOrderDto);
        if (ListUtil.isNull(storeOrderDtos)) {
            throw new IllegalArgumentException("订单不存在");

        }

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(storeOrderDtos.get(0).getShopId());
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        if (ListUtil.isNull(shopDtos)) {
            throw new IllegalArgumentException("店铺不存在");

        }
        ShopSmsDto shopSmsDto = new ShopSmsDto();
        shopSmsDto.setShopId(storeOrderDtos.get(0).getShopId());
        List<ShopSmsDto> shopSmsDtos = shopSmsV1InnerServiceSMOImpl.queryShopSmss(shopSmsDto);
        if (ListUtil.isNull(shopSmsDtos)) {
            return;
        }
        int smsCount = Integer.parseInt(shopSmsDtos.get(0).getSmsCount());
        if (smsCount < 1) {
            return;
        }

        //查询要发送员工
        PrivilegeDto basePrivilegeDto = new PrivilegeDto();
        basePrivilegeDto.setResource("/sendOrderSms");
        basePrivilegeDto.setStoreId(shopDtos.get(0).getStoreId());
        basePrivilegeDto.setShopId(storeOrderDtos.get(0).getShopId());
        List<UserDto> userDtos = privilegeV1InnerServiceSMOImpl.queryPrivilegeUsers(basePrivilegeDto);
        if (ListUtil.isNull(userDtos)) {
            return;
        }
        List<String> userIds = new ArrayList<>();
        for (UserDto userDto : userDtos) {
            if (userIds.contains(userDto.getUserId())) {
                continue;
            }
            try {
                doSendOrderSms(userDto.getUserId(), storeOrderDtos.get(0), shopSmsDtos.get(0), shopDtos.get(0));
            } catch (Exception e) {
                e.printStackTrace();
            }

            userIds.add(userDto.getUserId());
        }
    }

    private void doSendOrderSms(String userId, StoreOrderDto storeOrderDto, ShopSmsDto shopSmsDto, ShopDto shopDto) {


        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);
        if (ListUtil.isNull(userDtos)) {
            return;
        }



        String personId = storeOrderDto.getPersonId();
        userDto = new UserDto();
        userDto.setUserId(personId);
        List<UserDto> personUserDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);
        String personLink = "1";
        if (!ListUtil.isNull(personUserDtos)) {
            personLink = personUserDtos.get(0).getTel();
        }
        //【商城名称】新订单通知：订单号${order_id}，客户${customer_name}，电话${customer_phone}，总金额${total_amount}，请及时处理！
        String content = "新订单通知：订单号"+storeOrderDto.getOrderId()+"，客户"+storeOrderDto.getPersonName()+"，电话"+personLink+"，总金额"+storeOrderDto.getPayPrice()+"，请及时处理！";
        SendSmsFactory.sendShopOrderSms(userDtos.get(0).getTel(), storeOrderDto.getOrderId(), storeOrderDto.getPersonName(), personLink, storeOrderDto.getPayPrice());
        String requestId = DistributedLock.getLockUUID();
        String key = this.getClass().getSimpleName() + shopSmsDto.getShopId();

        try {
            //开启事务
            DistributedLock.waitGetDistributedLock(key, requestId);
            ShopSmsDto tmpShopSmsDto = new ShopSmsDto();
            tmpShopSmsDto.setSmsId(shopSmsDto.getSmsId());
            List<ShopSmsDto> shopSmsDtos = shopSmsV1InnerServiceSMOImpl.queryShopSmss(tmpShopSmsDto);

            ShopSmsPo shopSmsPo = new ShopSmsPo();
            int smsCount = Integer.parseInt(shopSmsDtos.get(0).getSmsCount());
            smsCount -=1;
            if(smsCount < 1){
                smsCount = 0;
            }
            shopSmsPo.setSmsCount(smsCount+"");
            shopSmsPo.setSmsId(shopSmsDto.getSmsId());
            shopSmsV1InnerServiceSMOImpl.updateShopSms(shopSmsPo);

            ShopSmsDetailPo shopSmsDetailPo = new ShopSmsDetailPo();
            shopSmsDetailPo.setSmsId(shopSmsDtos.get(0).getSmsId());
            shopSmsDetailPo.setSmsContent(content);
            shopSmsDetailPo.setLink(userDtos.get(0).getTel());
            shopSmsDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId("11"));
            shopSmsDetailPo.setShopName(shopDto.getShopName());
            shopSmsDetailPo.setShopId(shopDto.getShopId());
            shopSmsDetailV1InnerServiceSMOImpl.saveShopSmsDetail(shopSmsDetailPo);

        } finally {
            //清理事务信息
            DistributedLock.releaseDistributedLock(key, requestId);
        }
    }
}
